package icu.cqcai.xinsi.service.impl;

import icu.cqcai.xinsi.domain.User;
import icu.cqcai.xinsi.domain.dto.UserLoginRequest;
import icu.cqcai.xinsi.domain.dto.UserLoginResponse;
import icu.cqcai.xinsi.domain.dto.UserRegisterRequest;
import icu.cqcai.xinsi.mapper.UserMapper;
import icu.cqcai.xinsi.service.UserService;
import icu.cqcai.xinsi.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

/**
 * 用户服务实现类
 * 集成数据库持久化、密码加密和JWT认证
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    // 邮箱正则表达式验证
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
        "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
    );
    
    // 手机号正则表达式验证（中国大陆）
    private static final Pattern PHONE_PATTERN = Pattern.compile(
        "^1[3-9]\\d{9}$"
    );
    
    @Override
    public String register(UserRegisterRequest registerRequest) {
        System.out.println("=== 用户注册请求 ===");
        System.out.println("注册信息: " + registerRequest);
        
        // 1. 基本参数验证
        if (registerRequest.getUsername() == null || registerRequest.getUsername().trim().isEmpty()) {
            return "用户名不能为空";
        }
        if (registerRequest.getPassword() == null || registerRequest.getPassword().trim().isEmpty()) {
            return "密码不能为空";
        }
        if (registerRequest.getEmail() == null || registerRequest.getEmail().trim().isEmpty()) {
            return "邮箱不能为空";
        }
        
        // 2. 用户名格式验证
        String username = registerRequest.getUsername().trim();
        if (username.length() < 3 || username.length() > 20) {
            return "用户名长度应在3-20个字符之间";
        }
        if (!username.matches("^[a-zA-Z0-9_]+$")) {
            return "用户名只能包含字母、数字和下划线";
        }
        
        // 3. 密码强度验证
        String password = registerRequest.getPassword();
        if (password.length() < 6) {
            return "密码长度不能少于6位";
        }
        
        // 4. 确认密码验证
        if (!password.equals(registerRequest.getConfirmPassword())) {
            return "两次输入的密码不一致";
        }
        
        // 5. 邮箱格式验证
        String email = registerRequest.getEmail().trim();
        if (!EMAIL_PATTERN.matcher(email).matches()) {
            return "邮箱格式不正确";
        }
        
        // 6. 手机号格式验证（可选）
        String phone = registerRequest.getPhone();
        if (phone != null && !phone.trim().isEmpty()) {
            phone = phone.trim();
            if (!PHONE_PATTERN.matcher(phone).matches()) {
                return "手机号格式不正确";
            }
        }
        
        // 7. 检查用户名是否已存在
        if (isUsernameExists(username)) {
            return "用户名已存在";
        }
        
        // 8. 检查邮箱是否已存在
        if (isEmailExists(email)) {
            return "邮箱已被注册";
        }
        
        // 9. 密码加密
        String encodedPassword = passwordEncoder.encode(password);
        System.out.println("密码加密完成");
        
        // 10. 创建用户对象并保存到数据库
        User newUser = new User(username, encodedPassword, email, phone);
        try {
            int result = userMapper.insert(newUser);
            if (result > 0) {
                System.out.println("用户注册成功: " + username + ", ID: " + newUser.getId());
                return "注册成功";
            } else {
                return "注册失败，请稍后重试";
            }
        } catch (Exception e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            e.printStackTrace();
            return "注册失败，请稍后重试";
        }
    }
    
    @Override
    public UserLoginResponse login(UserLoginRequest loginRequest) {
        System.out.println("=== 用户登录请求 ===");
        System.out.println("登录信息: " + loginRequest);
        
        // 1. 基本参数验证
        if (loginRequest.getUsername() == null || loginRequest.getUsername().trim().isEmpty()) {
            return UserLoginResponse.failure("用户名不能为空");
        }
        if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
            return UserLoginResponse.failure("密码不能为空");
        }
        
        String username = loginRequest.getUsername().trim();
        String password = loginRequest.getPassword();
        
        // 2. 查找用户
        User user = findByUsername(username);
        if (user == null) {
            return UserLoginResponse.failure("用户不存在");
        }
        
        // 3. 验证密码（使用BCrypt）
        if (!passwordEncoder.matches(password, user.getPassword())) {
            System.out.println("密码验证失败: " + username);
            return UserLoginResponse.failure("密码错误");
        }
        
        // 4. 生成JWT令牌
        try {
            String token = jwtUtil.generateToken(username);
            System.out.println("用户登录成功: " + username + ", JWT Token生成完成");
            return UserLoginResponse.success(user, token);
        } catch (Exception e) {
            System.err.println("JWT令牌生成失败: " + e.getMessage());
            e.printStackTrace();
            return UserLoginResponse.failure("登录过程发生错误，请稍后重试");
        }
    }
    
    @Override
    public User findByUsername(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        try {
            return userMapper.findByUsername(username.trim());
        } catch (Exception e) {
            System.err.println("查找用户失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public boolean isUsernameExists(String username) {
        if (username == null || username.trim().isEmpty()) {
            return false;
        }
        try {
            return userMapper.existsByUsername(username.trim());
        } catch (Exception e) {
            System.err.println("检查用户名存在性失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean isEmailExists(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        try {
            return userMapper.existsByEmail(email.trim().toLowerCase());
        } catch (Exception e) {
            System.err.println("检查邮箱存在性失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean validateToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            return false;
        }
        try {
            return jwtUtil.validateToken(token.trim());
        } catch (Exception e) {
            System.err.println("验证JWT token失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public String getUsernameFromToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            return null;
        }
        try {
            return jwtUtil.getUsernameFromToken(token.trim());
        } catch (Exception e) {
            System.err.println("从JWT token提取用户名失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
